<template>
	<div class="boxes-table-page">
		<global-table
			:data-source="localTableAttr.data"
			:selected-row-keys="localTableAttr.selectedKeys"
			:loading="localTableAttr.loading"
			:columns="columns"
			:use-select="true"
			:operation-width="236"
			:show-operation="true"
			:custom-row="tableCustomRow"
			@selected="(rowKeys: any) => (localTableAttr.selectedKeys = rowKeys)"
		>
			<template #status="{ record }">
				<div class="status"><span v-if="record.status === 0" class="status-dot"></span>{{ C_Status(record.status) }}</div>
			</template>

			<template #serial="{ record }">
				<div class="sn-box">
					<span>{{ record.serial }}</span>
					<span v-if="hoveredRowId === record.id" class="copy-btn" @click="copySN(record.serial)">
						<global-svg-icon icon-name="file-copy-line" width="18px" height="18px"></global-svg-icon>
					</span>
				</div>
			</template>

			<template #faceSyncStatus="{ record }">
				<span :style="c_SyncPersonState(record.faceSyncStatus).style">{{ c_SyncPersonState(record.faceSyncStatus).text }}</span>
			</template>

			<template #operation="{ record }">
				<div class="operations">
					<div v-if="g6Permission.showBtn('details')" class="operation-item-btn" @click="PageButtonClick('details', record)">详情</div>

					<div v-if="g6Permission.showBtn('reset')" class="operation-item-btn" @click="PageButtonClick('reset', record)">重启</div>

					<a-dropdown v-model:open="record.visible" :placement="'bottomRight'" :trigger="'click'">
						<div v-if="cShowMoreBtn" class="operation-item-btn">
							更多
							<i v-if="record.visible" class="iconfont icon-arrow-up-s-line"></i>
							<i v-else class="iconfont icon-arrow-down-s-line"></i>
						</div>
						<template #overlay>
							<a-menu class="drop-menu">
								<a-menu-item v-if="g6Permission.showBtn('sync_person')" @click="PageButtonClick('single-sync-person', record)">
									同步人员数据
								</a-menu-item>

								<a-menu-item
									v-if="g6Permission.showBtn('algo-online-auth')"
									:disabled="record.status !== 1"
									@click="useAlgoAuthHooks.singleAuth('online', record.serial)"
									>在线授权
								</a-menu-item>
								<a-menu-item
									v-if="g6Permission.showBtn('algo-offline-auth')"
									:disabled="record.status !== 1"
									@click="useAlgoAuthHooks.singleAuth('offline', record.serial)"
									>离线授权
								</a-menu-item>
								<a-menu-item v-if="g6Permission.showBtn('alarm-conf')" @click="PageButtonClick('alarm-conf', record)">
									报警配置
								</a-menu-item>
								<a-menu-item v-if="g6Permission.showBtn('single-delete')" @click="PageButtonClick('single-delete', record)">
									删除
								</a-menu-item>
							</a-menu>
						</template>
					</a-dropdown>
				</div>
			</template>
		</global-table>

		<global-pagination
			:current="localTableAttr.current"
			:page-size="localTableAttr.pageSize"
			:total="localTableAttr.total"
			@change="setPagination"
		></global-pagination>
		<div class="bottom-operate">
			<global-table-batch-operation v-model:selected-rows="localTableAttr.selectedKeys">
				<template #Slot-Table-Btns>
					<div class="batch-operation">
						<a-button v-if="g6Permission.showBtn('algo-export-sn')" class="btn" :disabled="exportSnDisabled" @click="exportSn">
							<upload-outlined class="btn-icon"></upload-outlined>导出SN码
						</a-button>
						<a-button
							v-if="g6Permission.showBtn('algo-online-auth')"
							class="btn"
							:disabled="
								localTableAttr.data.filter((item: any) => localTableAttr.selectedKeys.includes(item.id) && item.status === 1).length === 0
							"
							@click="useAlgoAuthHooks.batchAuth(localTableAttr, 'online')"
						>
							<safety-certificate-outlined class="btn-icon"></safety-certificate-outlined>在线授权
						</a-button>
						<a-button
							v-if="g6Permission.showBtn('algo-offline-auth')"
							class="btn"
							:disabled="
								localTableAttr.data.filter((item: any) => localTableAttr.selectedKeys.includes(item.id) && item.status === 1).length === 0
							"
							@click="useAlgoAuthHooks.batchAuth(localTableAttr, 'offline')"
							><global-svg-icon
								icon-name="algo-auth-off-line"
								width="16px"
								height="16px"
								class="btn-icon"
								style="margin-right: 8px"
							></global-svg-icon
							>离线授权
						</a-button>
					</div>
				</template>
			</global-table-batch-operation>
		</div>
	</div>

	<!-- 在线授权 -->
	<a-modal
		v-model:open="useAlgoAuthHooks.onlineAuthVisible.value"
		title="在线授权 "
		:body-style="{ padding: '40px 32px 60px 32px' }"
		width="600px"
		:footer="null"
		:closable="false"
		:mask-closable="false"
	>
		<div v-if="!useAlgoAuthHooks.onlineAuthStatus.value" class="online-auth">
			<three-loading></three-loading>
			<p class="loading-text">正在获取授权文件，请稍等..</p>
		</div>
		<div v-else class="online-auth online-auth--success">
			<img src="@/global-assets/imgs/icon-success-fill.png" />
			<p class="status-text">授权成功</p>
			<a-button
				type="primary"
				@click="
					useAlgoAuthHooks.authComplete();
					refreshData();
				"
				>确定</a-button
			>
		</div>
	</a-modal>

	<!-- 离线授权 -->
	<a-modal
		v-model:open="useAlgoAuthHooks.offlineAuthVisible.value"
		title="离线授权"
		:body-style="{ padding: '40px 32px' }"
		:ok-button-props="{
			loading: useAlgoAuthHooks.offlineAuthLoading.value,
			disabled:
				!useAlgoAuthHooks.fileList.value.length || !useAlgoAuthHooks.fileList.value.filter((item: any) => item.status === 'done').length
		}"
		:footer="useAlgoAuthHooks.offlineAuthStatus.value ? null : undefined"
		:mask-closable="false"
		@ok="useAlgoAuthHooks.confirmOfflineAuth()"
		@cancel="useAlgoAuthHooks.authComplete()"
	>
		<div v-if="!useAlgoAuthHooks.offlineAuthStatus.value" class="offline-auth">
			<a-upload
				class="upload-component"
				:multiple="false"
				:file-list="useAlgoAuthHooks.fileList.value"
				:accept="'.lic,text/plain'"
				:max-count="1"
				:custom-request="useAlgoAuthHooks.customRequest"
				@change="useAlgoAuthHooks.handleChange"
			>
				<a-button>
					<upload-outlined></upload-outlined>
					上传授权文件
				</a-button>
				<template #removeIcon="{ file }">
					<span>
						<close-outlined v-if="file.status === 'uploading'" style="color: #fff"></close-outlined>
						<delete-outlined v-else style="color: #fff"></delete-outlined>
					</span>
				</template>
				<template #iconRender="{ file }">
					<link-outlined v-if="file.status === 'done'" style="color: rgba(61, 127, 233, 1)"></link-outlined>
					<file-outlined v-else-if="file.status === 'error'" style="color: rgba(250, 114, 96, 1)"></file-outlined>
					<reload-outlined v-else style="color: rgba(26, 111, 243, 1)"></reload-outlined>
				</template>
			</a-upload>
			<div class="remarks">
				请联系官方客服人员获取算法授权文件<br />
				客服电话：400-991-0655（周一至周五9:00-18:00）
			</div>
		</div>
		<div v-else class="offline-auth offline-auth--success">
			<img src="@/global-assets/imgs/icon-success-fill.png" />
			<p class="status-text">授权成功</p>
			<a-button
				type="primary"
				@click="
					useAlgoAuthHooks.authComplete();
					refreshData();
				"
				>确定</a-button
			>
		</div>
	</a-modal>

	<!-- 批量授权 -->
	<a-modal
		v-model:open="useAlgoAuthHooks.batchAuthVisible.value"
		:width="600"
		title="授权结果"
		:body-style="{ padding: '40px 32px' }"
		:ok-button-props="{
			loading: useAlgoAuthHooks.offlineAuthLoading.value,
			disabled:
				!useAlgoAuthHooks.fileList.value.length || !useAlgoAuthHooks.fileList.value.filter((item: any) => item.status === 'done').length
		}"
		:footer="null"
		:mask-closable="false"
		:closable="false"
		class="batch-auth"
	>
		<div class="auth-process">
			本次在线授权共 <span>{{ useAlgoAuthHooks.batchAuthData.value.length }}</span> 条，成功
			<span>{{ useAlgoAuthHooks.batchAuthData.value.filter((item) => item.status === 1).length }}</span
			>条， 失败<span class="status-error">{{ useAlgoAuthHooks.batchAuthData.value.filter((item) => item.status === 2).length }}</span
			>条
		</div>
		<a-table :columns="useAlgoAuthHooks.batchAuthColumns" :data-source="useAlgoAuthHooks.batchAuthData.value" :pagination="false">
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'status'">
					<span v-if="record.status === 0">授权中</span>
					<span v-else-if="record.status === 2" class="status-error">授权失败</span>
					<span v-else-if="record.status === 1">授权成功</span>
				</template>
			</template>
		</a-table>
		<div class="result-btn">
			<a-button
				type="primary"
				:disabled="useAlgoAuthHooks.batchAuthData.value.filter((item: any) => item.status === 0).length > 0"
				@click="
					useAlgoAuthHooks.authComplete();
					refreshData();
				"
				>知道了</a-button
			>
		</div>
	</a-modal>
</template>

<script setup lang="ts" name="BoxesTablePage">
import { g6Permission } from 'glasssix-utils-ts';
import type { G6TableHooks } from 'glasssix-vue3-hooks';
import { AlgoAuthApi } from '../../../api';
import { message } from 'ant-design-vue';
import { useAlgoAuth } from './algoAuthHooks';
import { ThreeLoading } from '../../index';
const props = withDefaults(defineProps<TsPros>(), {
	tableAttr: () => ({
		data: [],
		loading: false,
		selectedKeys: [],
		current: 1,
		pageSize: 10,
		total: 0,
		pageSizeOptions: [],
		searchObj: {}
	})
});

const emits = defineEmits<{
	(e: 'setPagination', current: number, pageSize: number): void;
	(e: 'pageButtonClick', btnCode: string, record: Record<string, any>): void;
}>();

const useAlgoAuthHooks = useAlgoAuth(); // 授权hooks

const c_SyncPersonState = computed(() => {
	return function (state: any) {
		if (state === 0) {
			return { style: { color: '#56C763' }, text: '全部成功' };
		}
		if (state === 1) {
			return { style: { color: '#F59700' }, text: '部分失败' };
		}
		if (state === 2) {
			return { style: { color: '#FA7260' }, text: '全部失败' };
		}
		return { style: { color: '' }, text: '同步中' };
	};
});

type TsPros = {
	tableAttr: G6TableHooks.TableAttr;
};

const localTableAttr = ref();
let tableAttrWatch = watchEffect(() => {
	console.log('666', props.tableAttr);

	localTableAttr.value = { ...props.tableAttr };
	console.log('666', localTableAttr.value);
});

// 刷新页面数据
const refreshData = () => {
	emits('pageButtonClick', 'refreshData', {});
};

// 分页
const setPagination = (current: number, pageSize: number): void => {
	emits('setPagination', current, pageSize);
};

const cShowMoreBtn = computed(() => {
	const flags = [g6Permission.showBtn('alarm-conf'), g6Permission.showBtn('single-delete')];
	return flags.some((flag) => !!flag);
});

const columns: TsGlobalType.TsTableColumn[] = [
	{ dataIndex: 'boxName', title: '设备名称', width: 214, ellipsis: true },
	{ dataIndex: 'serial', title: 'SN码', custom: true, width: 214, ellipsis: true },
	{ dataIndex: 'status', title: '状态', custom: true, width: 108, ellipsis: true },
	{ dataIndex: 'totalDeviceCount', title: '接入设备数', width: 118, ellipsis: true },
	{ dataIndex: 'firmwareVersion', title: '固件版本', width: 214, ellipsis: true },
	{ dataIndex: 'softwareVersion', title: '软件版本', ellipsis: true },
	{ dataIndex: 'faceSyncStatus', title: '人员同步状态', ellipsis: true, custom: true }
];
const C_Status = computed(() => {
	return function name(status: string | number) {
		return status === 0 ? '离线' : '在线';
	};
});

/**
 * -----------------------导出SN码-----------------------
 */
const exportSnDisabled = ref(false);
const hoveredRowId = ref();
const tableCustomRow = (record: any) => {
	return {
		onMouseenter: () => {
			hoveredRowId.value = record.id;
		}, // 鼠标移入行
		onMouseleave: () => {
			hoveredRowId.value = null;
		}
	};
};
const exportSn = async () => {
	localTableAttr.value.loading = true;
	console.log('666', localTableAttr.value);

	let snList = localTableAttr.value.data
		.map((item: { id: any; serial: any }) => {
			console.log('66', localTableAttr.value.selectedKeys);

			if (localTableAttr.value.selectedKeys.includes(item.id)) {
				return item.serial;
			}
		})
		.filter((item: any) => {
			if (item) {
				return item;
			}
		});
	let params = {
		snList: snList.toString()
	};
	if (exportSnDisabled.value) {
		return;
	}
	exportSnDisabled.value = true;
	const { data } = await AlgoAuthApi.exportSn(params);

	const href = window.URL.createObjectURL(new Blob([data?.data]));
	const a = document.createElement('a');
	a.href = href || '';
	const fileName = data?.title;
	a.download = decodeURIComponent(fileName);
	a.click();
	a.remove();
	localTableAttr.value.loading = false;
	exportSnDisabled.value = false;
};
const copySN = (sn: string) => {
	const textArea = document.createElement('textarea');
	textArea.value = sn;
	textArea.style.position = 'fixed';
	document.body.appendChild(textArea);
	textArea.select();

	try {
		const successful = document.execCommand('copy');
		const messageText = successful ? '复制成功' : '复制失败';
		message.success(messageText);
	} catch (err) {
		message.error('复制失败');
	}

	document.body.removeChild(textArea);
};

// 页面按钮click
const PageButtonClick = async (btnCode: string, record: Record<string, any> = {}): Promise<void> => {
	emits('pageButtonClick', btnCode, record);
};

onUnmounted(() => {
	tableAttrWatch();
});
</script>

<style lang="less" scoped>
.drop-menu {
	:deep(.ant-dropdown-menu-item) {
		// width: 100px;
		padding-left: 12px !important;

		&:hover {
			background-color: @mask01 !important;
		}
	}
}

.boxes-table-page {
	display: flex;
	height: calc(100vh - 76px - 44px - 180px);
	flex-direction: column;
	justify-content: space-between;

	.sn-box {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.copy-btn {
			// line-height: 28px;
			cursor: pointer;
		}
	}

	.status {
		display: flex;
		justify-content: flex-start;
		align-items: center;

		.status-dot {
			width: 6px;
			height: 6px;
			margin-right: 6px;
			border-radius: 50%;
			background: @danger01;
		}
	}

	.operations {
		display: flex;

		.operation-item-btn {
			margin-right: 16px;
			color: @link01;

			&:hover {
				color: #679ff6;
				opacity: 0.85;
				cursor: pointer;
			}

			&:active {
				color: #2f6bcb;
				cursor: pointer;
			}
		}

		.operation-item-btn:last-child {
			margin-right: 0;
		}
	}

	.bottom-operate {
		position: absolute;
		bottom: 0;
		left: 0;
		width: 100%;

		.global-table-batch-operation {
			border-radius: 0 0 8px 8px;
		}

		.batch-operation {
			display: flex;

			.btn {
				display: inline-block;
				margin-right: 8px;
				color: @text01;

				&:first-child {
					margin-left: 32px;
				}

				.btn-icon {
					color: @text02;
				}
			}
		}
	}
}

.online-auth {
	text-align: center;

	.loading-text {
		margin-top: 16px;
		font-size: 14px;
		font-weight: 700;
		font-style: normal;
		line-height: 22px;
		color: @text01;
	}

	&--success {
		// 授权成功样式
		text-align: center;

		.status-text {
			margin-top: 16px;
			margin-bottom: 24px;
			font-size: 14px;
			font-weight: 700;
			font-style: normal;
			line-height: 22px; /* 157.143% */
			color: @text01;
		}
	}
}

.offline-auth {
	.remarks {
		margin-top: 12px;
		font-size: 12px;
		font-weight: 400;
		font-style: normal;
		line-height: 20px;
		color: @text03;
	}

	.upload-component {
		color: @text01;

		:deep(.ant-upload-list) {
			background: none;
		}

		:deep(.anticon-paper-clip) {
			color: rgba(61, 127, 233, 1);
		}

		:deep(.ant-upload-list-item-card-actions) {
			.ant-btn-text {
				width: auto !important;
				padding: 0 !important;
			}
		}
	}

	&--success {
		// 授权成功样式
		text-align: center;

		.status-text {
			margin-top: 16px;
			margin-bottom: 24px;
			font-size: 14px;
			font-weight: 700;
			font-style: normal;
			line-height: 22px; /* 157.143% */
			color: @text01;
		}
	}
}

.batch-auth {
	.auth-process {
		margin-bottom: 30px;
		// text-align: center;
		color: @text01;

		span {
			display: inline-block;
			width: 16px;
			font-size: 18px;
			font-weight: 600;
			text-align: center;
			color: #3f5bc0;
		}

		.status-error {
			color: @danger01;
		}
	}

	.status-error {
		color: @danger01;
	}

	.result-btn {
		padding-top: 32px;
		text-align: center;
	}
}
</style>
